const fs = require("fs");

// 读取zh_tw_sources中的data文件
DataManager.loadDataFile = function (name, src) {
  const xhr = new XMLHttpRequest();
  const isHant = window.$gameGlobalManager.isHant();
  const hantTargetUrl = `zh_hant_sources/data/${src}`;
  const url = isHant ? hantTargetUrl : `/data/${src}`;
  xhr.open("GET", url);
  xhr.overrideMimeType("application/json");
  xhr.onload = function () {
    if (xhr.status < 400) {
      window[name] = JSON.parse(xhr.responseText);
      DataManager.onLoad(window[name]);
    }
  };
  xhr.onerror =
    this._mapLoader ||
    function () {
      DataManager._errorUrl = DataManager._errorUrl || url;
    };
  window[name] = null;
  xhr.send();
};

Bitmap.prototype._requestImage = function (url, language = "zh-cn") {
  if (!url) return;
  const originUrl = url;
  const hantTargetUrl = `zh_hant_sources/${url}`;

  const request = (url) => {
    if (Bitmap._reuseImages.length !== 0) {
      this._image = Bitmap._reuseImages.pop();
    } else {
      this._image = new Image();
    }

    if (this._decodeAfterRequest && !this._loader) {
      this._loader = ResourceHandler.createLoader(
        url,
        this._requestImage.bind(this, url),
        this._onError.bind(this)
      );
    }

    this._image = new Image();
    this._url = url;
    this._loadingState = "requesting";

    if (!Decrypter.checkImgIgnore(url) && Decrypter.hasEncryptedImages && !url.startsWith('data:image')) {
      this._loadingState = "decrypting";
      Decrypter.decryptImg(url, this);
    } else {
      this._image.src = url;

      this._image.addEventListener(
        "load",
        (this._loadListener = Bitmap.prototype._onLoad.bind(this))
      );
      this._image.addEventListener(
        "error",
        (this._errorListener =
          this._loader || Bitmap.prototype._onError.bind(this))
      );
    }
  };

  const isHant = window.$gameGlobalManager.isHant();
  const isHantImageExist = (url) => {
    let urls = hantTargetUrl.split(".");
    urls[urls.length - 1] = "rpgmvp";
    const mvpUrls = urls.join(".");
    return fs.existsSync(hantTargetUrl) || fs.existsSync(mvpUrls);
  };

  if (isHant && isHantImageExist(hantTargetUrl)) {
    request(hantTargetUrl);
  } else {
    request(originUrl);
  }
};
